package com.weiyv.Updater.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class NetTool {
    private static String TAG = "Weiyv_Updater";
    private static final NetTool instance = new NetTool();
    private static Context context;
    private static HttpClient httpClient;

    private NetTool() {
    }

    public static NetTool getInstance() {
        return instance;
    }

    public void init(Context context) {
        this.context = context;
        httpClient = new DefaultHttpClient();
    }

    public String getURL(String url) {
        return getURL(url, "UTF-8");
    }

    public String getURL(String url, String charSet) {
        StringBuffer res = new StringBuffer();
        try {
            HttpParams httpParams = httpClient.getParams();
//            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
//            HttpConnectionParams.setSoTimeout(httpParams, 5000);
            HttpResponse response = httpClient.execute(new HttpGet(url));
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charSet), 8192);
                String line = null;
                while ((line = reader.readLine()) != null)
                    res.append(line + "\n");
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res.toString();
    }

    public String getLocation() {
        String page = getURL("http://pv.sohu.com/cityjson", "GB2312");
        String cip = "未正确解析", cname = "未正确解析";
        if (page.contains("\"cip\"") && page.contains("\"cname\"")) {
            cip = page.substring(page.indexOf("cip") + 7, page.indexOf("\", \"cid"));
            cname = page.substring(page.indexOf("cname") + 9, page.indexOf("\"};"));
        }
        return "&IP=" + cip + "&City=" + cname;
    }

    public boolean isNetworkAvailable() {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netWorkInfo = cm.getActiveNetworkInfo();
            return (netWorkInfo != null && netWorkInfo.isAvailable());//检测网络是否可用
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String downloadFile(String fileURL) {
        String appPath = context.getFilesDir().toString();
        String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(fileURL);
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                Log.i(TAG, "http error when download update package. from " + fileURL);
                return null;
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            if (is == null)
                return null;
            FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
            byte[] buf = new byte[1024];
            int read;
            while ((read = is.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, read);
            }
            is.close();
            fileOutputStream.close();
            Log.i(TAG, "download complete");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return appPath + "/" + fileName;
    }
}

